package com.hexiang.ratelimit.store;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class RateLimiterStore {

    private final Map<String, RateLimiter> cache = new ConcurrentHashMap<>();

    public RateLimiter resolveRateLimit(String apiKey,long permitsPerSecond) {
        return cache.computeIfAbsent(apiKey, k ->  newRateLimiter(permitsPerSecond));
    }
    private RateLimiter newRateLimiter(long permitsPerSecond) {
        return RateLimiter.create(permitsPerSecond);
    }

}